<template>
  <div>
    <!-- 面包屑导航 -->
    <BreadCrumbs name1="用户管理" name2="用户列表"></BreadCrumbs>
    <!-- 卡片内容 -->
    <el-card>
      <el-row type="flex" justify="space-between">
        <el-col style="margin-left: 16px; display: flex; flex-wrap: wrap; white-space: nowrap">
          <el-form :inline="true" :model="queryInfo" ref="form" class="form-inline">
            <el-form-item label="用户性别" prop="gender">
              <el-select size="small" v-model="queryInfo.gender" clearable>
                <el-option label="男" :value="1"></el-option>
                <el-option label="女" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户标签" prop="tag">
              <el-input placeholder="请输入内容" size="small" v-model="queryInfo.tag" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="nick_name">
              <el-input
                placeholder="请输入内容"
                size="small"
                v-model="queryInfo.nick_name"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="getUserList">搜索</el-button>
              <el-button size="small" @click="reset()">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <dk-table
        ref="table"
        :column="column"
        :pagination="paginationObjs"
        :tableData="tableData"
        shadow="never"
        :height="tableHeight"
      >
        <template #today_status="{ scope }">
          <!-- 0正常，1警告 -->
          <!-- {{ scope.daily_health[0]? scope.daily_health[0].today_status : '' }} -->
          <span v-if="!scope.daily_health[0]"></span>
          <span
            v-else-if="scope.daily_health[0].today_status"
            style="
              background-color: #e52f10;
              width: 45px;
              height: 20px;
              box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 1);
            "
          ></span>
          <span
            v-else
            style="
              background-color: #089c14;
              width: 45px;
              height: 20px;
              box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 1);
            "
          ></span>
        </template>
      </dk-table>
    </el-card>

    <el-dialog
      top="20%"
      title="添加标签"
      :visible.sync="tag_dialog.visible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="tag_dialog.form"
        ref="tagForm"
        label-width="80px"
        :rules="tag_dialog.rules"
        style="padding-right: 40px"
      >
        <el-form-item label="标签" prop="tag" required>
          <el-input v-model="tag_dialog.form.tag"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tag_dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="tagOnSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="内容填写" :visible.sync="edit_dialog.visible" :close-on-click-modal="false">
      <el-form
        label-position="top"
        :model="edit_dialog.form"
        ref="editForm"
        label-width="180px"
        :rules="edit_dialog.rules"
        style="padding-right: 40px; max-height: 50vh; overflow: auto"
      >
        <el-form-item label="电话" prop="phone">
          <el-input v-model="edit_dialog.form.phone"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nick_name">
          <el-input v-model="edit_dialog.form.nick_name"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="edit_dialog.form.age"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="edit_dialog.form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="症状" prop="symptom">
          <el-select v-model="edit_dialog.form.symptom" multiple>
            <el-option
              v-for="(item, index) in edit_dialog.symptomOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="干体质量（斤）" prop="initial_dry_weight">
          <el-input v-model="edit_dialog.form.initial_dry_weight"></el-input>
        </el-form-item>
        <el-form-item label="今日体质量（斤）" prop="today_weight">
          <el-input v-model="edit_dialog.form.daily_health[0].today_weight"></el-input>
        </el-form-item>
        <el-form-item label="静息心率（次/分）" prop="initial_resting_heart_rate">
          <el-input v-model="edit_dialog.form.initial_resting_heart_rate"></el-input>
        </el-form-item>
        <el-form-item label="今日静息心率（次/分）" prop="today_resting_heart_rate">
          <el-input v-model="edit_dialog.form.daily_health[0].today_resting_heart_rate"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="edit_dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="editOnSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pick } from 'lodash';
export default {
  data() {
    return {
      tag_dialog: {
        visible: false,
        form: {
          id: '',
          tag: '',
        },
        rules: {
          tag: [
            {
              required: true,
              message: '请输入标签',
              trigger: 'blur',
            },
            {
              max: 20,
              message: '长度不能超过20个字符',
            },
          ],
        },
      },
      edit_dialog: {
        visible: false,
        form: {
          id: '',
          phone: '31',
          nick_name: 'test',
          age: 45,
          tag: '44rqwe11',
          gender: 0,
          initial_resting_heart_rate: 0,
          initial_dry_weight: 0,
          symptom: [
            // {
            //   id: 1,
            //   name: '花粉症',
            // },
          ],
          daily_health: [
            {
              today_dry_weight: '',
              today_weight: '',
              today_resting_heart_rate: '',
            },
          ],
        },
        symptomOptions: [],
        rules: {
          phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (!/^1[3456789]\d{9}$/.test(value)) {
                  callback(new Error('请输入正确的电话号码'));
                } else {
                  callback();
                }
              },
            }
          ],
          nick_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
          age: [
            { required: true, message: '请输入年龄', trigger: 'blur' },
            {
              // 必须是数字
              validator: (rule, value, callback) => {
                if (!/^[0-9]*$/.test(value)) {
                  callback(new Error('请输入数字'));
                } else {
                  callback();
                }
              },
            },
          ],
          tag: [{ required: true, message: '请输入标签', trigger: 'blur' }],
          gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
          symptom: [{ required: true, message: '请选择症状', trigger: 'change' }],
          initial_dry_weight: [
            { required: true, message: '请输入干体质量', trigger: 'blur' },
            {
              //  包括小数和数字
              validator: (rule, value, callback) => {
                if (!/^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)$/.test(value)) {
                  callback(new Error('请输入数字'));
                } else {
                  callback();
                }
              },
            },
          ],
          initial_resting_heart_rate: [
            { required: true, message: '请输入静息心率', trigger: 'blur' },
            {
              //  包括小数和数字
              validator: (rule, value, callback) => {
                if (!/^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]z\d+([eE][+-]?\d+)?)$/.test(value)) {
                  callback(new Error('请输入数字'));
                } else {
                  callback();
                }
              },
            },
          ],
        }, 
      },
      queryInfo: {
        nick_name: null,
        tag: null,
        gender: null,
      },
      tableData: [],
      column: [
        {
          value: 'phone',
          name: '手机号',
        },
        {
          value: 'nick_name',
          name: '用户名',
        },
        {
          value: 'role',
          name: '角色',
          format: (val) => (val === 'kinsfolk' ? '亲属' : val === 'patient' ? '患者' : '-'),
        },
        {
          value: 'gender',
          name: '性别',
          format: (val) => (val === 1 ? '男' : val === 2 ? '女' : '-'),
        },
        {
          value: 'age',
          name: '年龄',
        },
        {
          value: 'symptom',
          name: '合并症',
          format: (val) => {
            return val.map((i) => i.name).join('/') || '-';
          },
        },
        {
          value: 'visit_list',
          name: '访问次数',
          format: (val) => {
            if (!val) return 0;
            return JSON.parse(val).reduce((cur, acc) => {
              return cur + acc.count;
            }, 0);
          },
        },
        {
          value: 'initial_dry_weight',
          name: '干体质量（斤）',
        },
        {
          value: 'today_weight',
          name: '今日体质量（斤）',
        },
        {
          value: 'initial_resting_heart_rate',
          name: '静息心率（次/分）',
        },
        {
          value: 'today_resting_heart_rate',
          name: '今日静息心率（次/分）',
        },
        {
          width: 80,
          value: 'today_status',
          name: '今日症状',
          slot: true,
        },
        {
          width: 80,
          value: 'total_input',
          name: '今日入量',
        },
        {
          width: 80,
          value: 'total_output',
          name: '今日出量',
        },
        {
          value: 'tag',
          name: '标签',
          //   stateList: [
          //     { name: '未支付', value: 0 },
          //     { name: '微信支付', value: 1 },
          //     { name: '微信+积分支付', value: 2 },
          //   ],
        },
        {
          width: 250,
          value: 'id',
          name: '操作',
          fixed: 'right',
          type: 'button',
          buttonList: [
            {
              type: 'no-tooltip',
              name: '添加标签',
              fun: (row) => {
                this.tag_dialog.visible = true;
                Object.assign(this.tag_dialog.form, pick(row, Object.keys(this.tag_dialog.form)));
              },
              color: 'text',
            },
            {
              type: 'no-tooltip',
              name: '修改',
              fun: async (row) => {
                await this.getSymptomOptions();
                this.edit_dialog.visible = true;
                console.log(row);
                const pickObj = pick(row, Object.keys(this.edit_dialog.form));
                Object.assign(this.edit_dialog.form, pickObj, {
                  symptom: pickObj.symptom.map((i) => i.id),
                });
                console.log(this.edit_dialog.form);
              },
              color: 'text',
            },
            {
              type: 'no-tooltip',
              name: '详情',
              fun: (row) => {
                this.$router.push({
                  path: '/users/detail/' + row.id,
                });
              },
              color: 'text',
            },
            {
              type: 'no-tooltip',
              name: '删除',
              fun: (row) => {
                console.log(row);
                this.deleteMessageBox({
                  message: '是否确认删除该用户？',
                }).then(async () => {
                  // const { code, msg } = await this.$http.post('/api/user/base_info', {
                  //   user_id: row.id,
                  //   delete: true,
                  // });
                  const { code, msg } = await this.$http.delete('/api/user/' + row.id);

                  if (code) return this.$message.error(msg);
                  this.paginationObjs.page = 1;
                  this.$message.success(msg);
                  await this.getUserList();
                  this.getTableHeight.call(this);
                });
              },
              //   showFun: (row) => {
              // return row.status == 1;
              //   },
              color: 'text',
            },
          ],
        },
      ],
      paginationObjs: {
        paginationChange: function () {
          this.getUserList();
        }.bind(this),
        page: 1,
        limit: 10,
        total: 0,
      },
      userList: [],
    };
  },

  created() {
    this.getUserList();
    this.getTableHeight.call(this);
  },
  methods: {
    async getUserList() {
      const { data, code, msg } = await this.$http({
        url: '/api/user',
        methods: 'get',
        params: {
          ...this.queryInfo,
          page: this.paginationObjs.page,
          limit: this.paginationObjs.limit,
        },
      });
      if (code) return this.$message.error(msg);
      this.paginationObjs.page = data.page;
      this.paginationObjs.limit = data.limit;
      this.paginationObjs.total = data.total;
      this.tableData = data.result.map((item) => {
        return {
          ...item.internal_health,
          ...(item.daily_health[0] || []),
          ...(item.capacity_diary[0] || []),
          ...item,
        };
      });
    },
    async getSymptomOptions() {
      const { code, data, msg } = await this.$http.get('/api/symptom');
      if (code) return this.$message.error(msg);
      this.edit_dialog.symptomOptions = data.map((item) => {
        return {
          value: item.id,
          label: item.name,
        };
      });
    },
    async tagOnSubmit() {
      try {
        await this.$refs.tagForm.validate();
        const { code, msg } = await this.$http.post('/api/user/base_info', {
          tag: this.tag_dialog.form.tag,
          user_id: this.tag_dialog.form.id,
        });
        if (code) return this.$message.error(msg);
        this.tag_dialog.visible = false;
        this.$message.success('添加成功');
        this.$refs.tagForm.resetFields();
        await this.getUserList();
      } catch (error) {
        this.$message.error('请正确填写');
      }
    },
    async editOnSubmit() {
      console.log(this.edit_dialog.form);
      try {
        await this.$refs.editForm.validate();
        const user_id = this.edit_dialog.form.id;
        const res = await Promise.all([
          await this.$http.post('/api/user/base_info', {
            ...this.edit_dialog.form,
            user_id,
          }),
          await this.$http.post('/api/user/symptom', {
            symptom_ids: this.edit_dialog.form.symptom,
            user_id,
          }),
          await this.$http.post('/api/user/daily_health', {
            ...this.edit_dialog.form.daily_health,
            user_id,
          }),
        ]);

        if (res.code) return this.$message.error(res.msg);
        this.edit_dialog.visible = false;
        this.$message.success('修改成功');
        this.$refs.editForm.resetFields();
        await this.getUserList();
      } catch (error) {
        console.log(error);
        this.$message.error('请正确填写');
      }
    },
    async reset() {
      await this.$refs['form'].resetFields();
      await this.getUserList();
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.el-table {
  margin-top: 15px;
}

.el-pagination {
  margin-top: 15px;
}

.form-inline {
  display: flex;
  column-gap: 12px;
  flex-wrap: wrap;
}

::v-deep {
  .el-input {
    max-width: 120px !important;
  }
  .el-button--text {
    margin-right: 10px;
  }

  .el-form .el-input {
    width: 100%;
    max-width: none !important;
  }
}
</style>
